#!/usr/bin/python
import subprocess,os,re,datetime,sys,linecache,codecs,chardet

# Files Path
LOG_DIR = "E:\Log\Factory"+'\\'+str(datetime.date.today())       #Log directory
TCMD_ALL_NAME = "TCMD_all.log"                                   #Complete log
TCMD_ERROR_NAME = "TCMD_error.log"                               #Error log
TCMD_BAT = "E:\A_Document\TCMD_APK_TEST\milan-tcmd_M328.bat"     #TCMD script path

# Execute a script to output logs to TCMD.log
TCMD_CMD = "%s > %s\\%s" % (TCMD_BAT,LOG_DIR,TCMD_ALL_NAME)

# Execute cmd
def exec_cmd(cmd):
    # cmd = 'cmd.exe d:/start.bat'
    p = subprocess.Popen("cmd.exe /c" + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    curline = p.stdout.readline()
    while (curline != b''):
        print(curline)
        curline = p.stdout.readline()
    p.wait()
    if p.returncode != 0: #执行失败
        print ("exec cmd error: "+cmd+"\n")
        return False

# Read and write files
def op_file(filename,content=None):
    f = open(filename,'a+',encoding='utf-8')
    f.seek(0)
    if content:
        f.writelines(content)
        res = None
    else:
        res = f.readlines()
    f.close()
    return res

# Get file encoding format
def get_encoding(file_path,file):
    file_name = file_path+ '\\' + file
    with open(file_name,'rb') as f:
        tmp = chardet.detect(f.read())
        return tmp['encoding']

# Convert ansi file to utf-8
def ansi_to_utf8(file_path,file):
    encoding = get_encoding(file_path,file)
    print (encoding)
    if encoding != 'utf-8':
        file_name = file_path+ '\\' + file
        f= codecs.open(file_name,'r','ansi')
        ff= f.read()
        file_object= codecs.open(file_path+ '\\' + file, 'w', 'utf-8')
        file_object.write(ff)

# Create log directory
def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path) #查询目录是否存在
    if not isExists:
        os.makedirs(path) 
        print (path+' 创建成功')
        return True
    else:
        print (path+' 目录已存在')
        return False

# 遍历日志文件：
# 找出含有 error 或 Failure data received 的行和它的执行指令，按格式写入文件
def operation_log(file,f_path,d_file,d_path,error1,error2,obj_cmd):
    index = 0
    ansi_to_utf8(f_path,file)
    log_file = os.path.join(f_path, file)
    f = op_file(log_file)
    lis = []  # 存储错误日志
    for j in f:
        index += 1
        m = re.search(error1,j,re.IGNORECASE)
        n = re.search(error2,j,re.IGNORECASE)
        if (m or n) and index > 2:
            data_file = os.path.join(d_path, d_file)
            log_str = "文件名："+file+" 第"+str(index)+"行："+j+''
            lis.append(log_str)
            offset = 0
            for offset in range(13):
                offset += 1
                line = linecache.getline("%s/%s" % (f_path,file),index-15+offset)
                o_cmd = re.search(obj_cmd,line,re.IGNORECASE)
                if o_cmd:
                    lis.append(line[line.rfind('adb'):]+"\n")
                    linecache.clearcache()
                    break
                else:
                    linecache.clearcache()
    op_file(data_file,lis)

if __name__ == '__main__':
    if exec_cmd("adb root && adb remount") != False:
        mkdir(LOG_DIR)
        exec_cmd(TCMD_CMD)
        operation_log(TCMD_ALL_NAME,LOG_DIR,TCMD_ERROR_NAME,LOG_DIR,"error","Failure data received","adb shell tcmd_send")

